import Vue from 'vue'
import wx from 'weixin-js-sdk'
import * as http from './http'

// window.wx = wx;

// 判断浏览器类别
var ua = window.navigator.userAgent.toLowerCase()
console.log(ua)
var wechat = false
var ding = false
if (ua.match(/MicroMessenger/i) == 'micromessenger') {
  wechat = true
}
if (ua.match(/DingTalk/i) == 'dingtalk') {
  ding = true
  document.write('<script src="http://g.alicdn.com/dingding/dingtalk-jsapi/2.6.41/dingtalk.open.js"></script>')
}

Vue.prototype.$platform = {
  wechat: wechat,
  ding: ding
}

export function getUrlByPlatform() {
  let u = navigator.userAgent
  let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) //ios终端
  let url = ''
  if (isIOS) {
    url = location.href.split('#')[0]  //hash后面的部分如果带上ios中config会不对
  } else {
    url = location.href
  }
  return url
}

export function initConfig() {
  if (wechat) {
    let url = getUrlByPlatform()
    http.post('/api/trust/weixin/sign.do', {
      'url': url,
      'appid': appid
    }).then(v => {
      wx.config({
        debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: 'wx364672018a2c6634', // 必填，公众号的唯一标识
        timestamp: v['data'].timestamp, // 必填，生成签名的时间戳
        nonceStr: v['data'].nonceStr, // 必填，生成签名的随机串
        signature: v['data'].signature,// 必填，签名
        jsApiList: ['scanQRCode', 'chooseImage'] // 必填，需要使用的JS接口列表
      })
      wx.ready(() => {
        console.info('success')
      })
      wx.error(() => {
        console.info('error')
      })
    })
  } else if (ding) {

  }
}

export function chooseImages() {
  return new Promise((resolve, reject) => {
    let arr = []
    if (wechat) {
      wx.chooseImage({
        count: Window.options === undefined ? 5 : Window.options['max'],
        sizeType: ['original', 'compressed'],
        sourceType: ['album'],
        success: function (res) {
          res = res['localIds']
          if ($Utils.isNull(res)) return
          if (res.length == 0) {
            return
          }
          for (let i = 0; i < res.length; i++) {
            let localId = res[i]

            wx.getLocalImgData({
              localId: localId, // 图片的localID
              success: function (res) {
                let localData = res.localData
                if (localData.indexOf('data:image') != 0) {
                  localData = 'data:image/jpeg;base64,' + localData  // localData是图片的base64数据，可以用img标签显示
                }
                localData = localData.replace(/\r|\n/g, '').replace('data:image/jgp', 'data:image/jpeg')

                arr.push({type: 'Wechat', base64: localData, url: localData})
                /*if (i == (res.length - 1))*/
                resolve(arr)
              }
            })
          }
        }
      })
    } else {
      let input = document.createElement('input')
      input.setAttribute('type', 'file')
      input.setAttribute('accept', 'image/*')
      input.setAttribute('multiple', 'multiple')
      input.addEventListener('change', (e) => {
        let files = input.files
        if ($Utils.isNull(files)) return
        for (let i = 0; i < files.length; i++) {
          let file = files[i]
          let reader = new FileReader()
          reader.readAsDataURL(file)
          reader.onloadend = function () {
            let base64 = this.result
            arr.push({type: 'h5', base64: base64, url: base64})
            if (i == (files.length - 1)) resolve(arr)
          }
        }
      })
      input.click()
    }
  })
}

export function upload(base64) {
  return new Promise((resolve, reject) => {
    let blob = dataURLtoBlob(base64)
    let formData = new FormData()
    formData.append('file', blob, (new Date().getTime() + '.jpg'))
    http.post('/api/FormUpload/multiUpload.do', formData)
      .then(message => {
        let fileList = message['data']['resultData']
        resolve(fileList[0])
      }).catch(error => {
      reject(error)
    })
  })
}

export function dataURLtoBlob(base64) {
  let arr = base64.split(','), mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], {type: mime})
}

const wxConfig = {
  appid: 'wx364672018a2c6634',
  code: null,
  openid: null,
  route: null
}

export default {
  install: function (Vue, options) {
    let WechatTools = Vue.WechatTools = Vue.prototype.WechatTools = {
      initWeixin(route) {
        !wxConfig.route && (wxConfig.route = route)

        WechatTools.getCode(route)
          .then(WechatTools.getOpenId)
          .then(WechatTools.upsertOpenId)
          .then(WechatTools.sign)
      },
      sign() {
        if (wechat) {
          let url = getUrlByPlatform()
          http.post('/api/trust/weixin/sign.do', {
            'url': url,
            'appid': 'wx364672018a2c6634'
          }).then(v => {
            wx.config({
              debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
              appId: 'wx364672018a2c6634', // 必填，公众号的唯一标识
              timestamp: v['data'].timestamp, // 必填，生成签名的时间戳
              nonceStr: v['data'].nonceStr, // 必填，生成签名的随机串
              signature: v['data'].signature,// 必填，签名
              jsApiList: ['scanQRCode', 'chooseImage'] // 必填，需要使用的JS接口列表
            })
            wx.ready(() => {
              console.info('success')
            })
            wx.error(() => {
              console.info('error')
            })
          })
        }
      },
      getCode(route) {
        return new Promise(resolve => {
          wxConfig.code = route.query.code
          if (!wxConfig.code) {
            let redirect = 'https://open.weixin.qq.com/connect/oauth2/authorize'
            redirect += '?appid=' + wxConfig.appid
            redirect += '&redirect_uri=' + getUrlByPlatform()
            redirect += '&response_type=code'
            redirect += '&scope=snsapi_base'
            redirect += '#wechat_redirect'
            location.href = redirect
          } else {
            resolve(wxConfig.code)
          }
        })
      },
      getOpenId() {
        return new Promise(resolve => {
          http.post('/api/trust/weixin/getWeChatOpenId.do', {
            json: {
              appid: wxConfig.appid,
              code: wxConfig.code,
              secret: "886aa881a35647fc5ca20518f9590912",
            }
          }).then(v => {
            if (!v.data.openId) {
              delete wxConfig.route.query.code
              WechatTools.initWeixin(wxConfig.route)
            } else {
              wxConfig.openid = v.data.openId
              resolve(v.data.openId)
            }
          })
        })
      },
      upsertOpenId() {
        localStorage.setItem('openId', wxConfig.openid);
      }
    }
  }
}

export function UpdOpenId() {
  http.post('/api/wechat/openid/upsert.do', {
    data: {
      USERID: $Utils.getUserInfo()['PCRM_CZY02'],
      OPENID: wxConfig.openid
    }
  })
}
